using System;
using System.Net;
using System.Runtime.CompilerServices;

namespace Beetle;

public abstract class ServerBase : IDisposable
{
	private TcpServer a;

	private bool b;

	[CompilerGenerated]
	private int c;

	[CompilerGenerated]
	private bool d;

	[CompilerGenerated]
	private string e;

	public int Listens
	{
		[CompilerGenerated]
		get
		{
			return c;
		}
		[CompilerGenerated]
		set
		{
			c = value;
		}
	}

	public bool LittleEndian
	{
		[CompilerGenerated]
		get
		{
			return d;
		}
		[CompilerGenerated]
		set
		{
			d = value;
		}
	}

	public string Name
	{
		[CompilerGenerated]
		get
		{
			return e;
		}
		[CompilerGenerated]
		set
		{
			e = value;
		}
	}

	public TcpServer Server => a;

	public ServerBase()
	{
		Listens = 50;
		LittleEndian = true;
	}

	public void Open(string ip, int port)
	{
		Open(IPAddress.Parse(ip), port);
	}

	public void Open(int port)
	{
		Open(new IPEndPoint(IPAddress.Any, port));
	}

	public void Open(IPAddress ip, int port)
	{
		Open(new IPEndPoint(ip, port));
	}

	public void Open(IPEndPoint ep)
	{
		a = new TcpServer();
		a.LittleEndian = LittleEndian;
		OnBindEvent(a);
		a.Error += OnServerError;
		a.Open(ep, Listens);
		OnOpening();
	}

	protected virtual void OnServerError(object sender, TcpServerErrorArgs e)
	{
	}

	protected virtual void OnOpening()
	{
	}

	protected virtual void OnBindEvent(TcpServer server)
	{
		server.ChannelConnected += OnConnected;
		server.ChannelDisposed += OnDisposed;
		server.ChannelCreating += OnCreatingChannel;
	}

	protected virtual void OnCreatingChannel(object sender, ChannelCreatingArgs e)
	{
	}

	protected virtual void OnConnected(object sender, ChannelEventArgs e)
	{
		e.Channel.DataReceive = OnReceive;
		e.Channel.ChannelError += OnError;
		e.Channel.BeginReceive();
	}

	protected virtual void OnReceive(object sender, ChannelReceiveEventArgs e)
	{
	}

	protected virtual void OnDisposed(object sender, ChannelDisposedEventArgs e)
	{
	}

	protected virtual void OnError(object sender, ChannelErrorEventArgs e)
	{
	}

	protected virtual void OnServerDisposed()
	{
		if (a != null)
		{
			a.Dispose();
			a = null;
		}
	}

	public void Dispose()
	{
		lock (this)
		{
			if (!b)
			{
				b = true;
				OnServerDisposed();
			}
		}
	}
}
public abstract class ServerBase<T> : ServerBase where T : Package
{
	protected override void OnConnected(object sender, ChannelEventArgs e)
	{
		e.Channel.SetPackage<T>().ReceiveMessage = OnMessageReceive;
		e.Channel.ChannelError += OnError;
		e.Channel.BeginReceive();
	}

	protected virtual void OnMessageReceive(PacketRecieveMessagerArgs e)
	{
	}
}
